package com.tungse.minio.controller;

import com.tungse.minio.dto.FileUploadInfo;
import com.tungse.minio.service.FileUploadService;
import com.tungse.minio.dto.UploadProgress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/file")
public class FileUploadController {
    
    @Autowired
    private FileUploadService fileUploadService;
    
    // 初始化文件上传
    @PostMapping("/init")
    public ResponseEntity<?> initFileUpload(@RequestBody FileUploadInfo fileUploadInfo) {
        
        fileUploadService.initFileUpload(fileUploadInfo);
        return ResponseEntity.ok().build();
    }
    
    // 上传分片文件
    @PostMapping("/upload")
    public ResponseEntity<?> uploadChunk(
            @RequestParam String fileMd5,
            @RequestParam MultipartFile chunk,
            @RequestParam int chunkIndex) {
        
        try {
            boolean completed = fileUploadService.uploadChunk(fileMd5, chunk, chunkIndex);
            if (completed) {
                return ResponseEntity.ok().body("{\"status\": \"completed\"}");
            } else {
                return ResponseEntity.ok().body("{\"status\": \"success\"}");
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }
    
    // 获取上传进度
    @GetMapping("/progress/{fileMd5}")
    public ResponseEntity<?> getUploadProgress(@PathVariable String fileMd5) {
        UploadProgress progress = fileUploadService.getUploadProgress(fileMd5);
        if (progress == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(progress);
    }
}